package com.alibaba.dubbo.remoting.interceptor;

import java.net.InetAddress;
import java.util.Map;

import com.alibaba.dubbo.common.configure.ExtensionConfiguratorUtils;
import com.alibaba.dubbo.remoting.Interceptor;
import com.alibaba.dubbo.remoting.RemoteCalling;

public class InterceptorUtils {
	static public Interceptor getInterceptor() {
		return Holder.getInstance();
	}
	
	static class Holder{
		static com.alibaba.dubbo.remoting.Interceptor instance = null;
		static {
			Interceptor inst = (Interceptor) ExtensionConfiguratorUtils.getInstance().getValue(Interceptor.class);
			instance = new InterceptorWrapper(inst);
		}
		
		static com.alibaba.dubbo.remoting.Interceptor getInstance(){
			return instance;
		}
	}
	
	static class InterceptorWrapper implements Interceptor{
		Interceptor interceptor;
		public InterceptorWrapper(Interceptor interceptor){
			this.interceptor = interceptor;
		}
		
		@Override
		public boolean acceptAfterConnected(InetAddress remoteAddress) {
			if(interceptor != null){
				return interceptor.acceptAfterConnected(remoteAddress);
			}
			return true;
		}

		@Override
		public boolean acceptAfterHead(InetAddress remoteAddress, int total,
				int body) {
			if(interceptor != null){
				return interceptor.acceptAfterHead(remoteAddress, total, body);
			}
			return true;
		}

		@Override
		public boolean acceptAfterDecodeHeader(InetAddress remoteAddress,
				Map<String, String> headers, int data) {
			if(interceptor != null){
				return interceptor.acceptAfterDecodeHeader(remoteAddress, headers, data);
			}
			return true;
		}

		@Override
		public boolean acceptAfterDecodeBody(InetAddress remoteAddress,
				Map<String, String> headers, RemoteCalling calling) {
			if(interceptor != null){
				return interceptor.acceptAfterDecodeBody(remoteAddress, headers, calling);
			}
			return true;
		}

		@Override
		public boolean acceptBeforeEncodeBody(InetAddress remoteAddress,
				Map<String, String> headers) {
			if(interceptor != null){
				return interceptor.acceptBeforeEncodeBody(remoteAddress, headers);
			}
			return true;
		}

		@Override
		public boolean acceptBeforeEncodeHeader(InetAddress remoteAddress,
				Map<String, String> headers) {
			if(interceptor != null){
				return interceptor.acceptBeforeEncodeHeader(remoteAddress, headers);
			}
			return true;
		}
	}
}
